<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"
        name="viewport">
  <meta content="ie=edge" http-equiv="X-UA-Compatible">
  <title>RequestAnimationFrame</title>
  <style>
      .loading {
          width: 40px;
          height: 40px;
          background-color: aqua;

          font-size: 19px;
          line-height: 40px;
      }
  </style>
</head>

<body>
<!--进度条-->
<div class="loading" style=" width: 40px;height: 40px;background-color: aqua;line-height: 40px;">0%</div>
<!--<div class="loading">0%</div>-->
</body>
<script>
  // H5 新增的api  相当于setInterval(时间由js控制) 而RequestAnimationFrame间隔时间是由系统来控制的

  // 60HZ 一秒钟60次  1000ms/60 = 16.67ms
  /*  setInterval(()=>{
      console.log('setInterval')
    },17)*/
  /* let timer = requestAnimationFrame(function () {
     console.log('RequestAnimationFrame')
   })*/
  // cancelAnimationFrame(timer)
  /**
   * requestAnimationFrame 会把每一帧中的所有DOM操作集中起来，在一次重绘或回流中就完成，并且重绘或回流的时间间隔紧紧跟随浏览器的刷新频率，一般来说，这个频率为每秒60帧
   * 在隐藏或不可见的元素中，requestAnimationFrame将不会进行重绘或回流，这当然就意味着更少的的cpu，gpu和内存使用量。
   */
  /*if (!window.requestAnimationFrame) {
    setInterval(() => {
      console.log('setInterval')
    }, 17)
  } else {
    let timer = requestAnimationFrame(function () {
      console.log('RequestAnimationFrame')
    })
  }*/

  // 注意：style.width只能获取到内联的样式，但是不能获取内部和外部引用给样式
  let loading = document.querySelector('.loading')
  /*loading.onclick = function () {
    // console.log(getComputedStyle(loading).width)
    let timer = setInterval(function () {
      if (parseInt(loading.style.width) < 1000) {
        loading.style.width = parseInt(loading.style.width) + 10 + 'px'
        loading.innerHTML = parseInt(loading.style.width) / 10 + '%'
      } else {
        // loading.style.width = 40 + 'px'
        clearInterval(timer)

      }
    }, 17)
  }*/
  /*loading.onclick = function () {
    let timer = setTimeout(function fn() {
      if (parseInt(loading.style.width) < 1000) {
        loading.style.width = parseInt(loading.style.width) + 10 + 'px'
        loading.innerHTML = parseInt(loading.style.width) / 10 + '%'
        timer = setTimeout(fn, 17)
      } else {
        loading.style.width = 40 + 'px'
        // clearTimeout(timer)
      }
    }, 17)
  }*/
  loading.onclick = function () {
    let timer = requestAnimationFrame(function fn() {
      if (parseInt(loading.style.width) < 1000) {
        loading.style.width = parseInt(loading.style.width) + 10 + 'px'
        loading.innerHTML = parseInt(loading.style.width) / 10 + '%'
        timer = requestAnimationFrame(fn)
      } else {
        cancelAnimationFrame(timer)
      }
    })
  }
</script>
</html>